package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;
   


    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }


    @Override
    public void save(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }

    @Override
    @Transactional
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            bpmnInfoMapper.deleteByPrimaryKey(dictId);//dictId 就是 bpmnInfoId
           
    }
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    @Transactional
    public void deploy(String path, String bpmnType, String info) throws IOException {
        //需要的路径：  D:/upload/upload/2021/11/17/c62d4923-bfe4-43ce-84fb-8884fa5fc83d.bpmn
        // path路径：/upload/2021/11/17/c62d4923-bfe4-43ce-84fb-8884fa5fc83d.bpmn
        //SystemConfig.getProfile()   D:/upload
        //1.根据path找到流程文件
        File bpmnFile = new File(SystemConfig.getProfile(), path);
        //2.将流程文件部署到Activiti中
        FileInputStream fileInputStream = new FileInputStream(bpmnFile);
        Deployment deploy = repositoryService.createDeployment()
                .addInputStream(path, fileInputStream)
                .deploy();
        //3.根据生成部署对象，流程定义对象，封装BpmnInfo信息
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setBpmnType(bpmnType);  // 什么类型的审核
        bpmnInfo.setInfo(info);  //备注信息
        bpmnInfo.setDeploymentId(deploy.getId());
        bpmnInfo.setDeployTime(new Date()); // 部署时间
        //获取流程定义对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploy.getId())  // 根据部署ID 获取 对应的 流程定义
                .singleResult();
        bpmnInfo.setActProcessId(processDefinition.getId());
        bpmnInfo.setActProcessKey(processDefinition.getKey());
        bpmnInfo.setBpmnName(processDefinition.getName());
        //4.保存到数据库中
        bpmnInfoMapper.insert(bpmnInfo);
        fileInputStream.close();
    }

    @Override
    public InputStream getResourceAsStream(String deploymentId, String type) {
        //获取流程定义对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .singleResult();
        if("xml".equalsIgnoreCase(type)){
            //xml资源
            //获取xml资源名称
            String xmlResourceName = processDefinition.getResourceName(); ///upload/2021/11/17/60847e52-d840-4d4b-8874-a62b2ab6006b.bpmn
            //根据资源名称 获取输入流
            InputStream resourceAsStream = repositoryService.getResourceAsStream(deploymentId,xmlResourceName);
            return resourceAsStream;
        }else {
           //png资源
            //获取 bpmn模型对象 通过 流程实例ID
            BpmnModel model = repositoryService.getBpmnModel(processDefinition.getId());
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            //generateDiagram(bpmn模型对象,需要高亮的节点,需要高亮的连线,中文默认字体宋体)
            InputStream inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST, "宋体", "宋体", "宋体");
            return inputStream;
        }

    }

    @Override
    @Transactional
    public void delete(Long id) {
        //1.根据id 获取bpmn对象
        BpmnInfo bpmnInfo = this.get(id);
        //2.删除bpmn对象
        bpmnInfoMapper.deleteByPrimaryKey(id);
        //TODO
        //查询流程定义正在运行的流程实例
        //把流程实例关联的Businesskey  找到业务对象
        //3.获取流程定义对象
        //获取部署ID
        String deploymentId = bpmnInfo.getDeploymentId();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .singleResult();
        //4.删除Activiti中的流程定义对象
        repositoryService.deleteDeployment(deploymentId,true);
        //5.删除服务器上的文件
        String resourceName = processDefinition.getResourceName();
        File file = new File(SystemConfig.getProfile(),resourceName);
        if(file != null){
            file.delete();
        }
    }

    @Override
    public BpmnInfo getByBpmnType(String type) {
        return bpmnInfoMapper.getByBpmnType(type);
    }
}
